// 导入数据库模块
const db = require("../db/index.js");

// 评论
exports.comment = (req, res) => {
	const comment = req.body;
	const sql = `insert into COMMENT(DATE,ownerId,fromId,content)values(?,?,?,?)`;
	db.query(
		sql,
		[
			comment.DATE,
			comment.ownerId,
			comment.fromId,
			comment.content,
		],
		(err, result) => {
			if (err) {
				throw new Error("Server Error");
			}
			res.send({
				code: 200,
			});
		}
	);
};

// 回复
exports.reply = (req, res) => {
	const comment = req.body;
	const sql = `insert into reply(ownerId,commentId,DATE,fromId,content,toId,toAvatar)values(?,?,?,?,?,?,?)`;
	db.query(
		sql,
		[
			comment.ownerId,
			comment.commentId,
			comment.DATE,
			comment.fromId,
			comment.content,
			comment.toId,
			comment.toAvatar,
		],
		(err, result) => {
			if (err) {
				throw new Error("Server Error");
			}
			res.send({
				code: 200,
			});
		}
	);
};

// 根据启事id获取所有的评论
exports.getCommentById = (req, res) => {
	const sql = `SELECT c.id,c.DATE,c.ownerId ,c.fromId,c.content,u.head
	FROM COMMENT c
	LEFT JOIN users u
	ON c.fromId = u.user_id
	where c.ownerId = ?
	GROUP BY c.id`;
	db.query(sql, req.query.id, (err, results) => {
		if (err) {
			throw new Error("Server Error");
		}
		res.send({
			code: 200,
			data: results,
		});
	});
};

exports.getAllComment = (req, res) => {
  const sql = `
  SELECT c.id,c.DATE,c.ownerId ,c.fromId,c.content,u.head
  FROM COMMENT c
  LEFT JOIN users u
  ON c.fromId = u.user_id
  GROUP BY c.id`
  db.query(sql, (err, result) => {
    if (err) {
      throw new Error("Server Error");
    }
    res.send({
      code: 200,
      data: result,
    });
  })
}

// 根据启事id获取所有的回复
exports.getReplyById = (req, res) => {
	const sql = `SELECT r.id,r.DATE,r.ownerId ,r.fromId,r.content,u.head,r.commentId,r.toAvatar,r.toId
	FROM reply r
	LEFT JOIN users u
	ON r.fromId = u.user_id
	where r.ownerId = ?
	GROUP BY r.id`;
	db.query(sql, req.query.id, (err, results) => {
		if (err) {
			throw new Error("Server Error");
		}
		res.send({
			code: 200,
			data: results,
		});
	});
};

// 根据id删除评论
exports.deleteCommentById = (req, res) => {
	const sql = `DELETE FROM COMMENT WHERE id = ?`;
	db.query(sql, req.query.id, (err, results) => {
		if (err) {
			throw new Error("Server Error");
		}
		res.send({
			code: 200,
		});
	});
};

// 根据id删除回复
exports.deleteReplyById = (req, res) => {
	const sql = `DELETE FROM reply WHERE id = ?`;
	db.query(sql, req.query.id, (err, results) => {
		if (err) {
			throw new Error("Server Error");
		}
		res.send({
			code: 200,
		});
	});
};
